import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/order_model/order_buy_incubation_list_model.dart';
import 'package:yysk_app/model/order_model/order_sale_list_model.dart';
import 'package:yysk_app/model/order_model/get_pay_token_model.dart';
import 'package:yysk_app/model/order_model/order_list_model.dart';
import 'package:yysk_app/model/user_prop_model/blind_list_transfer_model.dart';
import 'package:yysk_app/model/user_prop_model/collection_list_transfer_model.dart';
import 'package:yysk_app/model/user_prop_model/prop_list_transfer_model.dart';
import 'package:yysk_app/net/api/order_api.dart';
import 'package:yysk_app/net/api/product_api.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/pages/nft_pages/pay_pages/confirm_payment/confirm_payment_page.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:oktoast/oktoast.dart';

class OrderController extends GetxController {
  final GlobalController globalController = Get.find();
  final orderBuyList = RxList<OrderListItem>();
  final orderBuyIncubationList = RxList<OrderBuyIncubationListItem>();
  final orderSaleList = RxList<OrderSaleListItem>();
  final orderTransferListCollection =
      RxList<CollectionListTransferItem>(); //转赠藏品
  final orderTransferListBlind = RxList<BlindListTransferItem>(); //转赠盲盒
  final orderTransferListProp = RxList<PropListTransferItem>(); //转赠道具
  final ScrollController buyScrollController = ScrollController();
  final ScrollController buyIncubationScrollController = ScrollController();
  final ScrollController saleScrollController = ScrollController();
  final statusCode = ''.obs; // ''全部 0待支付 10已完成 20已取消
  final statusSaleCode = '0'.obs; // ''0已锁单 10已售出 20已取消
  final buyTabCode = 'product'.obs; // product商品 incubation孵化
  final jumpTab = 'product'.obs; // product商品 incubation孵化
  final activeTab = 'buy'.obs;
  final productType = 'PRODUCT'.obs;
  int buyPageNum = 1;
  int buyPageSize = 20;

  int salePageNum = 1;
  int salePageSize = 20;

  int buyIncubationPageNum = 1;
  int buyIncubationPageSize = 20;

  int transferPageNum = 1;
  int transferPageSize = 20;

  @override
  void onInit() {
    super.onInit();
    final params = Get.parameters ?? {};
    final args = Get.arguments ?? {};
    productType.value =
        params['productType'] ?? (args['productType'] ?? 'PRODUCT');
    jumpTab.value = params['jumpTab'] ?? (args['jumpTab'] ?? 'product');
    buyTabCode.value = jumpTab.value;

    changeTab('buy');
    activeTab.value = 'buy';
    if (productType.value == 'PRODUCT') {
      //藏品的订单
      getBuyProductOrder();
    } else if (productType.value == 'INCUBATION') {
      // 孵化订单
      getBuyIncubationOrder();
    }
    buyScrollController.addListener(() {
      if (buyScrollController.position.pixels ==
          buyScrollController.position.maxScrollExtent) {
        getBuyProductOrder(loadMore: true);
      }
    });
    buyIncubationScrollController.addListener(() {
      if (buyIncubationScrollController.position.pixels ==
          buyIncubationScrollController.position.maxScrollExtent) {
        getBuyIncubationOrder(loadMore: true);
      }
    });
    saleScrollController.addListener(() {
      if (saleScrollController.position.pixels ==
          saleScrollController.position.maxScrollExtent) {
        getSaleOrder(loadMore: true);
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    buyIncubationScrollController.dispose();
    saleScrollController.dispose();
    saleScrollController.dispose();
  }

  // 切换主tab 购买订单 出售订单
  changeTab(String code) {
    if (code == activeTab.value) {
      return;
    }
    activeTab.value = code;
    statusCode.value = ''; // 切换默认展示全部
    if (code == 'buy') {
      buyTabCode.value = 'product';
      getBuyProductOrder();
    } else if (code == 'sale') {
      buyTabCode.value = 'incubation';
      statusSaleCode.value = '0';
      getSaleOrder();
    }
  }

  // 订单类型 全部 待付款 已完成 已关闭
  changeBuyTypeStatus(String val) {
    statusCode.value = val;
    if (buyTabCode.value == 'product') {
      getBuyProductOrder();
    } else {
      getBuyIncubationOrder();
    }
  }

  // 订单类型 已锁单 已售出 已取消
  changeSaleTypeStatus(String val) {
    statusSaleCode.value = val;
    getSaleOrder();
  }

  // 二级tab切换 藏品发售 品牌孵化
  changeBuyTabStatus(String val) {
    buyTabCode.value = val;
    statusCode.value = '';
    if (val == 'product') {
      getBuyProductOrder();
    } else {
      getBuyIncubationOrder();
    }
  }

  // 购买的孵化订单
  Future<void> getBuyIncubationOrder({loadMore = false}) async {
    if (loadMore) {
      buyIncubationPageNum++;
    } else {
      buyIncubationPageNum = 1;
    }

    var params = {
      'pageNum': buyIncubationPageNum,
      'pageSize': buyIncubationPageSize,
      'orderStatus': statusCode.value,
    };

    try {
      await http.netFetch<OrderBuyIncubationListModel>(
        OrderUrl.getOrdersByPage,
        params: params,
        success: (result) {
          List<OrderBuyIncubationListItem> list = result.data?.list ?? [];
          if (loadMore && list.isEmpty) {
            buyIncubationPageNum--;
          }
          if (!loadMore) {
            orderBuyIncubationList.clear();
          }
          orderBuyIncubationList.addAll(list);
        },
      );
    } catch (e) {
      debugPrint(e.toString());
      if (loadMore) {
        buyIncubationPageNum--;
      }
    }
  }

  //首发订单
  Future<void> getBuyProductOrder({loadMore = false}) async {
    if (loadMore) {
      buyPageNum++;
    } else {
      buyPageNum = 1;
    }

    var params = {
      'pageNum': buyPageNum,
      'pageSize': buyPageSize,
      'orderStatus': statusCode.value,
    };

    try {
      await http.netFetch<OrderListModel>(
        OrderUrl.orderList,
        params: params,
        success: (result) {
          List<OrderListItem> list = result.data?.list ?? [];
          if (loadMore && list.isEmpty) {
            buyPageNum--;
          }
          if (!loadMore) {
            orderBuyList.clear();
          }
          orderBuyList.addAll(list);
        },
      );
    } catch (e) {
      debugPrint(e.toString());
      if (loadMore) {
        buyPageNum--;
      }
    }
  }

  //售出订单
  Future<void> getSaleOrder({loadMore = false}) async {
    if (loadMore) {
      salePageNum++;
    } else {
      salePageNum = 1;
    }

    var params = {
      'pageNum': salePageNum,
      'pageSize': salePageSize,
      'orderStatus': statusSaleCode.value,
    };

    try {
      await http.netFetch<OrderSaleListModel>(
        OrderUrl.getOrdersBySellPage,
        params: params,
        success: (result) {
          List<OrderSaleListItem> list = result.data?.list ?? [];
          if (loadMore && list.isEmpty) {
            salePageNum--;
          }
          if (!loadMore) {
            orderSaleList.clear();
          }
          orderSaleList.addAll(list);
        },
      );
    } catch (e) {
      debugPrint(e.toString());
      if (loadMore) {
        salePageNum--;
      }
    }
  }

  cancelOrder(id) {
    if (buyTabCode.value == 'product') {
      cancelBuyOrder(id);
    } else {
      cancelIncubationOrder(id);
    }
  }

  cancelBuyOrder(id) {
    http.netFetch<dynamic>(
      OrderUrl.orderCancel,
      params: {'orderId': id},
      success: (result) {
        showToast('订单取消成功');
        getBuyProductOrder();
        Navigator.of(Get.context!).pop();
      },
    );
  }

  cancelIncubationOrder(id) {
    http.netFetch<dynamic>(
      ProductApi.incubationOrderCancel,
      params: {'orderId': id},
      success: (result) {
        showToast('订单取消成功');
        getBuyIncubationOrder();
        Navigator.of(Get.context!).pop();
      },
    );
  }

  payToken(dynamic sn, dynamic type) {
    if (type == 'PRODUCT') {
      getPayToken(sn, type);
    } else {
      getIncubationPayToken(sn, type);
    }
  }

  //获取孵化支付令牌
  Future<dynamic> getIncubationPayToken(dynamic sn, dynamic type) async {
    try {
      http.netFetch<GetPayTokenModel>(
        OrderUrl.getIncubationPayToken,
        method: Method.post,
        params: {
          "businessType": 'INCUBATE',
          'orderIds': ['$sn'],
        },
        success: (result) {
          Get.toNamed(
            '${ConfirmPaymentPage.path}?cashierToken=${result.data?.cashierToken}&accessToken=${result.data?.accessToken}&businessType=VIRTUAL_GOODS&clientType=web',
            arguments: {
              'cashierToken': result.data?.cashierToken,
              'accessToken': result.data?.accessToken,
              'businessType': 'DEBUT',
            },
          );
          // 在 Web 环境下调用 JavaScript
          // window.location.href =
          //     '${Env.envConfig.envPayUrl}?cashierToken=${result.data?.cashierToken}&accessToken=${result.data?.accessToken}&businessType=PHYSICAL_GOODS&clientType=web';
          return result;
        },
      );
    } catch (e) {
      consoleLog(e.toString());
    }
  }

  //获取首发藏品令牌
  Future<dynamic> getPayToken(dynamic sn, dynamic type) async {
    try {
      http.netFetch<GetPayTokenModel>(
        OrderUrl.getPayToken,
        method: Method.post,
        params: {"businessType": type, 'orderId': sn},
        success: (result) {
          Get.toNamed(
            '${ConfirmPaymentPage.path}?cashierToken=${result.data?.cashierToken}&accessToken=${result.data?.accessToken}&businessType=VIRTUAL_GOODS&clientType=web',
            arguments: {
              'cashierToken': result.data?.cashierToken,
              'accessToken': result.data?.accessToken,
              'businessType': 'DEBUT',
            },
          );
          // 在 Web 环境下调用 JavaScript
          // window.location.href =
          //     '${Env.envConfig.envPayUrl}?cashierToken=${result.data?.cashierToken}&accessToken=${result.data?.accessToken}&businessType=PHYSICAL_GOODS&clientType=web';
          return result;
        },
      );
    } catch (e) {
      consoleLog(e.toString());
    }
  }
}
